<template>
  <div>
    <h2>欢迎回来，{{ user?.name }}</h2>
    <button @click="logout">退出登录</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import authApi from '../api/auth'
import { useRouter } from 'vue-router'

const router = useRouter()
const user = ref(null)

onMounted(async () => {
  try {
    const res = await authApi.getUser()
    user.value = res.data
  } catch {
    router.push('/login')
  }
})

const logout = async () => {
  await authApi.logout()
  localStorage.removeItem('token')
  router.push('/login')
}
</script>
